﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Abp.UI;
using Abp.Web.Models;
using Abp.Web.Mvc.Models;
using MyCompanyName.AbpZeroTemplate.IO;
using MyCompanyName.AbpZeroTemplate.Web.Controllers;

namespace MyCompanyName.AbpZeroTemplate.Web.Areas.Mpa.Controllers
{
    public class ImageController : AbpZeroTemplateControllerBase
    {
        private IAppFolders _appFolders;
        public ImageController(IAppFolders appFolders)
        {
            _appFolders = appFolders;
        }
        // GET: Mpa/Image
        public JsonResult Upload()
        {
            try
            {
                //Check input
                if (Request.Files.Count <= 0 || Request.Files[0] == null)
                {
                    throw new UserFriendlyException(L("ProfilePicture_Change_Error"));
                }

                var file = Request.Files[0];

                if (file.ContentLength > 5242880) //1MB.
                {
                    throw new UserFriendlyException(L("ProfilePicture_Warn_SizeLimit"));
                }

                //Check file type & format
                var fileImage = Image.FromStream(file.InputStream);
                if (!fileImage.RawFormat.Equals(ImageFormat.Jpeg) && !fileImage.RawFormat.Equals(ImageFormat.Png))
                {
                    throw new ApplicationException("Uploaded file is not an accepted image file !");
                }

                

                //Save new picture
                var fileInfo = new FileInfo(file.FileName);
                var fileName = Guid.NewGuid() + fileInfo.Extension;
                var filePath = Path.Combine(_appFolders.ProductImageFolder, fileName);
                file.SaveAs(filePath);

                using (var bmpImage = new Bitmap(filePath))
                {
                    return Json(new MvcAjaxResponse(new { fileName = fileName, width = bmpImage.Width, height = bmpImage.Height }), "text/html");
                }
            }
            catch (UserFriendlyException ex)
            {
                return Json(new MvcAjaxResponse(new ErrorInfo(ex.Message)));
            }
        }
    }
}